<?php

declare(strict_types=1);

namespace app\admin\service;

use app\admin\model\CustomerContact as CustomerContactModel;
use app\admin\common\ServiceResponse;
use app\admin\service\SystemSMChannel as SystemSMChannelService;


class CustomerContact
{

    use ServiceResponse;

    protected $model;
    public function __construct()
    {
        $this->model = new CustomerContactModel();
    }

    /**
     * @describe 获取联系人列表
     * @author: Bobo
     * @date: 2024-06-05 18:02:26 
     * @param [] type
     * @return Renderable
     */
    public function getList($where, $page, $limit, $operator_id = 0)
    {
        if (0 >= $page || 100 < $limit) {
            return $this->error(100002);
        }

        $query = CustomerContactModel::alias('a')->join('db_customer b', 'b.id = a.cusid', 'LEFT')->where($where);

        if (!isSuperAdmin($operator_id)) {
            $query->whereRaw("b.owner = {$operator_id} OR FIND_IN_SET('{$operator_id}', b.partner)");
        } else {
            $query->whereRaw("b.owner != 0");
        }

        $total = $query->count();
        $list = $query
            ->field('a.id,a.cusid,a.cname,a.gender,a.birthday,a.phone,a.email,a.qq,a.telegram,a.wechat,a.whatsapp,a.dingtalk,a.country,a.address,a.department,a.position,a.level,a.decision,a.tags,a.remark,a.creator,a.updater,a.create_time,a.update_time')
            ->page($page, $limit)
            ->select()
            ->toArray();


        if (empty($list)) {
            return $this->success(['list' => [], 'total' => 0]);
        }

        // 1. 一次性收集所有需要查询的ID
        $creatorIds = array_column($list, 'creator');
        $updaterIds = array_column($list, 'updater');
        $cusidIds = array_column($list, 'cusid');

        // 合并去重，减少查询次数
        $operatorIds = array_unique(array_filter(array_merge($creatorIds, $updaterIds)));

        // 2. 一次性查询所有需要的数据
        $operators = [];
        $customers = [];

        if (!empty($operatorIds)) {
            $operators = $this->model->name('Operator')->whereIn('id', $operatorIds)->column('cname', 'id');
        }

        if (!empty($cusidIds)) {
            $customers = $this->model->name('Customer')->whereIn('id', $cusidIds)->column('cusname', 'id');
        }

        // 3. 获取枚举值（只获取一次）
        $enums = $this->model->getFieldEnum('ALL');
        $level = $enums['level'] ?? [];
        $gender = $enums['gender'] ?? [];
        $decision = $enums['decision'] ?? [];

        // 4. 只使用一个循环处理所有数据
        foreach ($list as &$item) {
            // 设置关联值
            $item['creator_value'] = $operators[$item['creator']] ?? '';
            $item['updater_value'] = $operators[$item['updater']] ?? '';
            $item['cusid_value'] = $customers[$item['cusid']] ?? '';

            // 设置枚举值
            $item['level_value'] = $level[$item['level']] ?? '';
            $item['gender_value'] = $gender[$item['gender']] ?? '';
            $item['decision_value'] = $decision[$item['decision']] ?? '';
        }

        return $this->success(['list' => $list, 'total' => $total]);
    }

    /**
     * 获取联系人详情
     * @param int $id 联系人ID
     */
    public function getOneById($id)
    {
        $data = CustomerContactModel::field('id,cusid,cname,gender,birthday,phone,email,qq,telegram,wechat,whatsapp,dingtalk,country,address,department,position,level,decision,tags,remark,creator,updater,create_time,update_time')->find($id)->toArray();

        $data['creator_value'] = $this->model->name('Operator')->where('id', $data['creator'])->value('cname');
        $data['updater_value'] = $this->model->name('Operator')->where('id', $data['updater'])->value('cname');
        $data['cusid_value'] = $this->model->name('Customer')->where('id', $data['cusid'])->value('cusname');
        $enums = $this->model->getFieldEnum('ALL');
        $level = $enums['level'] ?? [];
        $gender = $enums['gender'] ?? [];
        $decision = $enums['decision'] ?? [];
        $data['level_value'] = $level[$data['level']] ?? '';
        $data['gender_value'] = $gender[$data['gender']] ?? '';
        $data['decision_value'] = $decision[$data['decision']] ?? '';
        return $this->success($data);
    }

    /**
     * 创建联系人
     * @param array $data 创建联系人的数据
     */
    public function create($data)
    {
        try {
            $res = CustomerContactModel::create($data);
            if ($res) {
                return $this->success();
            } else {
                return $this->error(500001);
            }
        } catch (\Throwable $th) {
            return $this->error(500001, '服务器内部错误：' . $th->getMessage());
        }
    }

    /**
     * 更新联系人
     * @param int $id 联系人ID
     * @param array $data 更新联系人的数据
     */
    public function update($data)
    {
        $res = CustomerContactModel::where('id', $data['id'])->find();
        if (!$res) {
            return false;
        }
        foreach ($data as $key => $value) {
            if ($res->$key != $value) {
                $res->$key = $value;
            }
        }

        $result = $res->save();
        if ($result) {
            return $this->success();
        } else {
            return $this->error(500001);
        }
    }

    /**
     * 删除联系人
     * @param int $id 联系人ID
     */
    public function delete($id)
    {
        return CustomerContactModel::where('id', $id)->delete();
    }

    /**
     * @describe 批量逻辑删除联系人
     * @author: Bobo
     * @date: 2024-06-26 14:53:00 
     * @param [arr] @required $ids ID数组
     * @return Renderable
     */
    public function batchLogicalDelete($ids)
    {
        try {
            $cusidArr = $this->model::where('id', 'in', $ids)->field('id,cusid,cname')->select()->toArray();
            foreach ($cusidArr as $key => $value) {
                $isExitCustomer = $this->model->table('db_customer')->where([
                    'id' => $value['cusid'],
                    'is_del' => 0
                ])->find();
                if ($isExitCustomer) {
                    return $this->error(500001, '联系人' . $value['cname'] . '关联客户' . $isExitCustomer['cusname'] . '状态正常，无法删除联系人');
                }
            }
            $this->model::where('id', 'in', $ids)->update(['is_del' => time()]);
            return $this->success();
        } catch (\Throwable $th) {
            return $this->error(500001, $th->getMessage());
        }
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2024-08-06 19:08:17 
     * @param [type] @required
     * @return Renderable
     */
    /**
     * @describe
     * @author: Bobo
     * @date: 2024-07-23 10:34:00 
     * @param [type] @required
     * @return Renderable
     */
    public function getFieldEnum($field)
    {
        $model = new CustomerContactModel();
        $res = $model->getFieldEnum($field);

        $tripartiteChannelService = new SystemSMChannelService();
        $res['tripartite_channel'] = $tripartiteChannelService->getSelectData()['data'];
        return [
            'code' => 0,
            'data' => $res
        ];
    }
}
